from numpy import *
import os
import operator
def classify0(inX, dataSet, labels, k):
    dataSetSize = dataSet.shape[0]
    diffMat = tile(inX, (dataSetSize, 1)) - dataSet
    sdiffMat = diffMat ** 2
    sqDistances = sdiffMat.sum(axis=1)
    distances = sqDistances ** 0.5
    SortedDistances = distances.argsort()
    classCount = {}
    for i in range(k):
        voteLabel = labels[SortedDistances[i]]
        classCount[voteLabel] = classCount.get(voteLabel, 0) + 1
    sortClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
    return sortClassCount[0][0]
def img2Vector(filename):
    file = open(filename)
    returnVector = zeros((1, 1024))
    for i in range(32):
        lineStr = file.readline()
        #print(lineStr)
        for j in range(32):
            returnVector[0, 32 * i + j] = int(lineStr[j])
    return returnVector
def HandWritingClassify():
    Labels = []
    Trainlist = os.listdir('trainingDigits')
    m = len(Trainlist)
    TrainVector = zeros((m, 1024))
    for i in range(m):
        fileNameStr = Trainlist[i]
        fileName = fileNameStr.split('.')[0]
        classNumStr = int(fileName.split('_')[0])
        Labels.append(classNumStr)
        TrainVector[i,:] = img2Vector('trainingDigits/%s' % fileNameStr)
    TestList = os.listdir('testDigits')
    mTest = len(TestList)
    errorCount = 0.0
    for i in range(mTest):
        fileNameStr = TestList[i]
        fileName = fileNameStr.split('.')[0]
        classNumStr = int(fileName.split('_')[0])
        testVector = img2Vector('testDigits/%s' % fileNameStr)
        classifyResult = classify0(testVector, TrainVector, Labels, 3)
        print('识别结果为：%d,   正确结果为：%d' % (classifyResult, classNumStr))
        if(classifyResult != classNumStr):
            errorCount += 1.0
    print('错误数量为：%d' % errorCount)
    print('错误率为：%f' % (errorCount / float(mTest)))
#returnVector = img2Vector('testDigits/0_13.txt')
HandWritingClassify()
